home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlcall.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  62.7 KB  |  1,841 lines

  1. NAME
  2.        perlcall - Perl calling conventions from C
  3.  
  4. DESCRIPTION
  5.        The purpose of this document is to show you how to call
  6.        Perl subroutines directly from C, i.e. how to write
  7.        callbacks.
  8.  
  9.        Apart from discussing the C interface provided by Perl for
  10.        writing callbacks the document uses a series of examples
  11.        to show how the interface actually works in practice.  In
  12.        addition some techniques for coding callbacks are covered.
  13.  
  14.        Examples where callbacks are necessary include
  15.  
  16.        o An Error Handler
  17.             You have created an XSUB interface to an
  18.             application's C API.
  19.  
  20.             A fairly common feature in applications is to allow
  21.             you to define a C function that will be called
  22.             whenever something nasty occurs. What we would like
  23.             is to be able to specify a Perl subroutine that will
  24.             be called instead.
  25.  
  26.        o An Event Driven Program
  27.             The classic example of where callbacks are used is
  28.             when writing an event driven program like for an X
  29.             windows application.  In this case your register
  30.             functions to be called whenever specific events
  31.             occur, e.g. a mouse button is pressed, the cursor
  32.             moves into a window or a menu item is selected.
  33.  
  34.        Although the techniques described here are applicable when
  35.        embedding Perl in a C program, this is not the primary
  36.        goal of this document.  There are other details that must
  37.        be considered and are specific to embedding Perl. For
  38.        details on embedding Perl in C refer to the perlembed
  39.        manpage.
  40.  
  41.        Before you launch yourself head first into the rest of
  42.        this document, it would be a good idea to have read the
  43.        following two documents - the perlxs manpage and the
  44.        perlguts manpage.
  45.  
  46. THE PERL_CALL FUNCTIONS
  47.        Although this stuff is easier to explain using examples,
  48.        you first need be aware of a few important definitions.
  49.  
  50.        Perl has a number of C functions that allow you to call
  51.        Perl subroutines.  They are
  52.  
  53.            I32 perl_call_sv(SV* sv, I32 flags) ;
  54.            I32 perl_call_pv(char *subname, I32 flags) ;
  55.            I32 perl_call_method(char *methname, I32 flags) ;
  56.            I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  57.  
  58.        The key function is perl_call_sv.  All the other functions
  59.        are fairly simple wrappers which make it easier to call
  60.        Perl subroutines in special cases. At the end of the day
  61.        they will all call perl_call_sv to actually invoke the
  62.        Perl subroutine.
  63.  
  64.        All the perl_call_* functions have a flags parameter which
  65.        is used to pass a bit mask of options to Perl.  This bit
  66.        mask operates identically for each of the functions.  The
  67.        settings available in the bit mask are discussed in the
  68.        section on FLAG VALUES.
  69.  
  70.        Each of the functions will now be discussed in turn.
  71.  
  72.        perl_call_sv
  73.             perl_call_sv takes two parameters, the first, sv, is
  74.             an SV*.  This allows you to specify the Perl
  75.             subroutine to be called either as a C string (which
  76.             has first been converted to an SV) or a reference to
  77.             a subroutine. The section, Using perl_call_sv, shows
  78.             how you can make use of perl_call_sv.
  79.  
  80.        perl_call_pv
  81.             The function, perl_call_pv, is similar to
  82.             perl_call_sv except it expects its first parameter to
  83.             be a C char* which identifies the Perl subroutine you
  84.             want to call, e.g. perl_call_pv("fred", 0).  If the
  85.             subroutine you want to call is in another package,
  86.             just include the package name in the string, e.g.
  87.             "pkg::fred".
  88.  
  89.        perl_call_method
  90.             The function perl_call_method is used to call a
  91.             method from a Perl class.  The parameter methname
  92.             corresponds to the name of the method to be called.
  93.             Note that the class that the method belongs to is
  94.             passed on the Perl stack rather than in the parameter
  95.             list. This class can be either the name of the class
  96.             (for a static method) or a reference to an object
  97.             (for a virtual method).  See the perlobj manpage for
  98.             more information on static and virtual methods and
  99.             the section on Using perl_call_method for an example
  100.             of using perl_call_method.
  101.  
  102.        perl_call_argv
  103.             perl_call_argv calls the Perl subroutine specified by
  104.             the C string stored in the subname parameter. It also
  105.             takes the usual flags parameter.  The final
  106.             parameter, argv, consists of a NULL terminated list
  107.             of C strings to be passed as parameters to the Perl
  108.             subroutine.  See Using perl_call_argv.
  109.  
  110.        All the functions return an integer. This is a count of
  111.        the number of items returned by the Perl subroutine. The
  112.        actual items returned by the subroutine are stored on the
  113.        Perl stack.
  114.  
  115.        As a general rule you should always check the return value
  116.        from these functions.  Even if you are expecting only a
  117.        particular number of values to be returned from the Perl
  118.        subroutine, there is nothing to stop someone from doing
  119.        something unexpected - don't say you haven't been warned.
  120.  
  121. FLAG VALUES
  122.        The flags parameter in all the perl_call_* functions is a
  123.        bit mask which can consist of any combination of the
  124.        symbols defined below, OR'ed together.
  125.  
  126.        G_SCALAR
  127.  
  128.        Calls the Perl subroutine in a scalar context.  This is
  129.        the default context flag setting for all the perl_call_*
  130.        functions.
  131.  
  132.        This flag has 2 effects
  133.  
  134.        1.   it indicates to the subroutine being called that it
  135.             is executing in a scalar context (if it executes
  136.             wantarray the result will be false).
  137.  
  138.        2.   it ensures that only a scalar is actually returned
  139.             from the subroutine.  The subroutine can, of course,
  140.             ignore the wantarray and return a list anyway. If so,
  141.             then only the last element of the list will be
  142.             returned.
  143.  
  144.        The value returned by the perl_call_* function indicates
  145.        how may items have been returned by the Perl subroutine -
  146.        in this case it will be either 0 or 1.
  147.  
  148.        If 0, then you have specified the G_DISCARD flag.
  149.  
  150.        If 1, then the item actually returned by the Perl
  151.        subroutine will be stored on the Perl stack - the section
  152.        Returning a Scalar shows how to access this value on the
  153.        stack.  Remember that regardless of how many items the
  154.        Perl subroutine returns, only the last one will be
  155.        accessible from the stack - think of the case where only
  156.        one value is returned as being a list with only one
  157.        element.  Any other items that were returned will not
  158.        exist by the time control returns from the perl_call_*
  159.        function.  The section Returning a list in a scalar
  160.        context shows an example of this behaviour.
  161.        G_ARRAY
  162.  
  163.        Calls the Perl subroutine in a list context.
  164.  
  165.        As with G_SCALAR, this flag has 2 effects
  166.  
  167.        1.   it indicates to the subroutine being called that it
  168.             is executing in an array context (if it executes
  169.             wantarray the result will be true).
  170.  
  171.        2.   it ensures that all items returned from the
  172.             subroutine will be accessible when control returns
  173.             from the perl_call_* function.
  174.  
  175.        The value returned by the perl_call_* function indicates
  176.        how may items have been returned by the Perl subroutine.
  177.  
  178.        If 0, the you have specified the G_DISCARD flag.
  179.  
  180.        If not 0, then it will be a count of the number of items
  181.        returned by the subroutine. These items will be stored on
  182.        the Perl stack.  The section Returning a list of values
  183.        gives an example of using the G_ARRAY flag and the
  184.        mechanics of accessing the returned items from the Perl
  185.        stack.
  186.  
  187.        G_DISCARD
  188.  
  189.        By default, the perl_call_* functions place the items
  190.        returned from by the Perl subroutine on the stack.  If you
  191.        are not interested in these items, then setting this flag
  192.        will make Perl get rid of them automatically for you.
  193.        Note that it is still possible to indicate a context to
  194.        the Perl subroutine by using either G_SCALAR or G_ARRAY.
  195.  
  196.        If you do not set this flag then it is very important that
  197.        you make sure that any temporaries (i.e. parameters passed
  198.        to the Perl subroutine and values returned from the
  199.        subroutine) are disposed of yourself.  The section
  200.        Returning a Scalar gives details of how to explicitly
  201.        dispose of these temporaries and the section Using Perl to
  202.        dispose of temporaries discusses the specific
  203.        circumstances where you can ignore the problem and let
  204.        Perl deal with it for you.
  205.  
  206.        G_NOARGS
  207.  
  208.        Whenever a Perl subroutine is called using one of the
  209.        perl_call_* functions, it is assumed by default that
  210.        parameters are to be passed to the subroutine.  If you are
  211.        not passing any parameters to the Perl subroutine, you can
  212.        save a bit of time by setting this flag.  It has the
  213.        effect of not creating the @_ array for the Perl
  214.        subroutine.
  215.        Although the functionality provided by this flag may seem
  216.        straightforward, it should be used only if there is a good
  217.        reason to do so.  The reason for being cautious is that
  218.        even if you have specified the G_NOARGS flag, it is still
  219.        possible for the Perl subroutine that has been called to
  220.        think that you have passed it parameters.
  221.  
  222.        In fact, what can happen is that the Perl subroutine you
  223.        have called can access the @_ array from a previous Perl
  224.        subroutine.  This will occur when the code that is
  225.        executing the perl_call_* function has itself been called
  226.        from another Perl subroutine. The code below illustrates
  227.        this
  228.  
  229.            sub fred
  230.              { print "@_\n"  }
  231.  
  232.            sub joe
  233.              { &fred }
  234.  
  235.            &joe(1,2,3) ;
  236.  
  237.        This will print
  238.  
  239.            1 2 3
  240.  
  241.        What has happened is that fred accesses the @_ array which
  242.        belongs to joe.
  243.  
  244.        G_EVAL
  245.  
  246.        It is possible for the Perl subroutine you are calling to
  247.        terminate abnormally, e.g. by calling die explicitly or by
  248.        not actually existing.  By default, when either of these
  249.        of events occurs, the process will terminate immediately.
  250.        If though, you want to trap this type of event, specify
  251.        the G_EVAL flag.  It will put an eval { } around the
  252.        subroutine call.
  253.  
  254.        Whenever control returns from the perl_call_* function you
  255.        need to check the $@ variable as you would in a normal
  256.        Perl script.
  257.  
  258.        The value returned from the perl_call_* function is
  259.        dependent on what other flags have been specified and
  260.        whether an error has occurred.  Here are all the different
  261.        cases that can occur
  262.  
  263.        o    If the perl_call_* function returns normally, then
  264.             the value returned is as specified in the previous
  265.             sections.
  266.  
  267.        o    If G_DISCARD is specified, the return value will
  268.             always be 0.
  269.        o    If G_ARRAY is specified and an error has occurred,
  270.             the return value will always be 0.
  271.  
  272.        o    If G_SCALAR is specified and an error has occurred,
  273.             the return value will be 1 and the value on the top
  274.             of the stack will be undef. This means that if you
  275.             have already detected the error by checking $@ and
  276.             you want the program to continue, you must remember
  277.             to pop the undef from the stack.
  278.  
  279.        See Using G_EVAL for details of using G_EVAL.
  280.  
  281.        G_KEEPERR
  282.  
  283.        You may have noticed that using the G_EVAL flag described
  284.        above will always clear the $@ variable and set it to a
  285.        string describing the error iff there was an error in the
  286.        called code.  This unqualified resetting of $@ can be
  287.        problematic in the reliable identification of errors using
  288.        the eval {} mechanism, because the possibility exists that
  289.        perl will call other code (end of block processing code,
  290.        for example) between the time the error causes $@ to be
  291.        set within eval {}, and the subsequent statement which
  292.        checks for the value of $@ gets executed in the user's
  293.        script.
  294.  
  295.        This scenario will mostly be applicable to code that is
  296.        meant to be called from within destructors, asynchronous
  297.        callbacks, signal handlers, __DIE__ or __WARN__ hooks, and
  298.        tie functions.  In such situations, you will not want to
  299.        clear $@ at all, but simply to append any new errors to
  300.        any existing value of $@.
  301.  
  302.        The G_KEEPERR flag is meant to be used in conjunction with
  303.        G_EVAL in perl_call_* functions that are used to implement
  304.        such code.  This flag has no effect when G_EVAL is not
  305.        used.
  306.  
  307.        When G_KEEPERR is used, any errors in the called code will
  308.        be prefixed with the string "\t(in cleanup)", and appended
  309.        to the current value of $@.
  310.  
  311.        The G_KEEPERR flag was introduced in Perl version 5.002.
  312.  
  313.        See Using G_KEEPERR for an example of a situation that
  314.        warrants the use of this flag.
  315.  
  316.        Determining the Context
  317.  
  318.        As mentioned above, you can determine the context of the
  319.        currently executing subroutine in Perl with wantarray. The
  320.        equivalent test can be made in C by using the GIMME macro.
  321.        This will return G_SCALAR if you have been called in a
  322.        scalar context and G_ARRAY if in an array context. An
  323.        example of using the GIMME macro is shown in section Using
  324.        GIMME.
  325.  
  326. KNOWN PROBLEMS
  327.        This section outlines all known problems that exist in the
  328.        perl_call_* functions.
  329.  
  330.        1.   If you are intending to make use of both the G_EVAL
  331.             and G_SCALAR flags in your code, use a version of
  332.             Perl greater than 5.000.  There is a bug in version
  333.             5.000 of Perl which means that the combination of
  334.             these two flags will not work as described in the
  335.             section FLAG VALUES.
  336.  
  337.             Specifically, if the two flags are used when calling
  338.             a subroutine and that subroutine does not call die,
  339.             the value returned by perl_call_* will be wrong.
  340.  
  341.        2.   In Perl 5.000 and 5.001 there is a problem with using
  342.             perl_call_* if the Perl sub you are calling attempts
  343.             to trap a die.
  344.  
  345.             The symptom of this problem is that the called Perl
  346.             sub will continue to completion, but whenever it
  347.             attempts to pass control back to the XSUB, the
  348.             program will immediately terminate.
  349.  
  350.             For example, say you want to call this Perl sub
  351.  
  352.                 sub fred
  353.                 {
  354.                     eval { die "Fatal Error" ; }
  355.                     print "Trapped error: $@\n"
  356.                         if $@ ;
  357.                 }
  358.  
  359.             via this XSUB
  360.  
  361.                 void
  362.                 Call_fred()
  363.                     CODE:
  364.                     PUSHMARK(sp) ;
  365.                     perl_call_pv("fred", G_DISCARD|G_NOARGS) ;
  366.                     fprintf(stderr, "back in Call_fred\n") ;
  367.  
  368.             When Call_fred is executed it will print
  369.  
  370.                 Trapped error: Fatal Error
  371.  
  372.             As control never returns to Call_fred, the "back in
  373.             Call_fred" string will not get printed.
  374.  
  375.             To work around this problem, you can either upgrade
  376.             to Perl 5.002 (or later), or use the G_EVAL flag with
  377.             perl_call_* as shown below
  378.  
  379.                 void
  380.                 Call_fred()
  381.                     CODE:
  382.                     PUSHMARK(sp) ;
  383.                     perl_call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
  384.                     fprintf(stderr, "back in Call_fred\n") ;
  385.  
  386. EXAMPLES
  387.        Enough of the definition talk, let's have a few examples.
  388.  
  389.        Perl provides many macros to assist in accessing the Perl
  390.        stack.  Wherever possible, these macros should always be
  391.        used when interfacing to Perl internals.  Hopefully this
  392.        should make the code less vulnerable to any changes made
  393.        to Perl in the future.
  394.  
  395.        Another point worth noting is that in the first series of
  396.        examples I have made use of only the perl_call_pv
  397.        function.  This has been done to keep the code simpler and
  398.        ease you into the topic.  Wherever possible, if the choice
  399.        is between using perl_call_pv and perl_call_sv, you should
  400.        always try to use perl_call_sv.  See Using perl_call_sv
  401.        for details.
  402.  
  403.        No Parameters, Nothing returned
  404.  
  405.        This first trivial example will call a Perl subroutine,
  406.        PrintUID, to print out the UID of the process.
  407.  
  408.            sub PrintUID
  409.            {
  410.                print "UID is $<\n" ;
  411.            }
  412.  
  413.        and here is a C function to call it
  414.  
  415.            static void
  416.            call_PrintUID()
  417.            {
  418.                dSP ;
  419.  
  420.                PUSHMARK(sp) ;
  421.                perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  422.            }
  423.  
  424.        Simple, eh.
  425.  
  426.        A few points to note about this example.
  427.  
  428.        1.   Ignore dSP and PUSHMARK(sp) for now. They will be
  429.             discussed in the next example.
  430.        2.   We aren't passing any parameters to PrintUID so
  431.             G_NOARGS can be specified.
  432.  
  433.        3.   We aren't interested in anything returned from
  434.             PrintUID, so G_DISCARD is specified. Even if PrintUID
  435.             was changed to actually return some value(s), having
  436.             specified G_DISCARD will mean that they will be wiped
  437.             by the time control returns from perl_call_pv.
  438.  
  439.        4.   As perl_call_pv is being used, the Perl subroutine is
  440.             specified as a C string. In this case the subroutine
  441.             name has been 'hard-wired' into the code.
  442.  
  443.        5.   Because we specified G_DISCARD, it is not necessary
  444.             to check the value returned from perl_call_pv. It
  445.             will always be 0.
  446.  
  447.        Passing Parameters
  448.  
  449.        Now let's make a slightly more complex example. This time
  450.        we want to call a Perl subroutine, LeftString, which will
  451.        take 2 parameters - a string ($s) and an integer ($n).
  452.        The subroutine will simply print the first $n characters
  453.        of the string.
  454.  
  455.        So the Perl subroutine would look like this
  456.  
  457.            sub LeftString
  458.            {
  459.                my($s, $n) = @_ ;
  460.                print substr($s, 0, $n), "\n" ;
  461.            }
  462.  
  463.        The C function required to call LeftString would look like
  464.        this.
  465.  
  466.            static void
  467.            call_LeftString(a, b)
  468.            char * a ;
  469.            int b ;
  470.            {
  471.                dSP ;
  472.  
  473.                PUSHMARK(sp) ;
  474.                XPUSHs(sv_2mortal(newSVpv(a, 0)));
  475.                XPUSHs(sv_2mortal(newSViv(b)));
  476.                PUTBACK ;
  477.  
  478.                perl_call_pv("LeftString", G_DISCARD);
  479.            }
  480.  
  481.        Here are a few notes on the C function call_LeftString.
  482.  
  483.        1.   Parameters are passed to the Perl subroutine using
  484.             the Perl stack.  This is the purpose of the code
  485.             beginning with the line dSP and ending with the line
  486.             PUTBACK.
  487.  
  488.        2.   If you are going to put something onto the Perl
  489.             stack, you need to know where to put it. This is the
  490.             purpose of the macro dSP - it declares and
  491.             initializes a local copy of the Perl stack pointer.
  492.  
  493.             All the other macros which will be used in this
  494.             example require you to have used this macro.
  495.  
  496.             The exception to this rule is if you are calling a
  497.             Perl subroutine directly from an XSUB function. In
  498.             this case it is not necessary to explicitly use the
  499.             dSP macro - it will be declared for you
  500.             automatically.
  501.  
  502.        3.   Any parameters to be pushed onto the stack should be
  503.             bracketed by the PUSHMARK and PUTBACK macros.  The
  504.             purpose of these two macros, in this context, is to
  505.             automatically count the number of parameters you are
  506.             pushing. Then whenever Perl is creating the @_ array
  507.             for the subroutine, it knows how big to make it.
  508.  
  509.             The PUSHMARK macro tells Perl to make a mental note
  510.             of the current stack pointer. Even if you aren't
  511.             passing any parameters (like the example shown in the
  512.             section No Parameters, Nothing returned) you must
  513.             still call the PUSHMARK macro before you can call any
  514.             of the perl_call_* functions - Perl still needs to
  515.             know that there are no parameters.
  516.  
  517.             The PUTBACK macro sets the global copy of the stack
  518.             pointer to be the same as our local copy. If we
  519.             didn't do this perl_call_pv wouldn't know where the
  520.             two parameters we pushed were - remember that up to
  521.             now all the stack pointer manipulation we have done
  522.             is with our local copy, not the global copy.
  523.  
  524.        4.   The only flag specified this time is G_DISCARD. Since
  525.             we are passing 2 parameters to the Perl subroutine
  526.             this time, we have not specified G_NOARGS.
  527.  
  528.        5.   Next, we come to XPUSHs. This is where the parameters
  529.             actually get pushed onto the stack. In this case we
  530.             are pushing a string and an integer.
  531.  
  532.             See the section the section on XSUB'S and the
  533.             Argument Stack in the perlguts manpage for details on
  534.             how the XPUSH macros work.
  535.  
  536.        6.   Finally, LeftString can now be called via the
  537.             perl_call_pv function.
  538.  
  539.        Returning a Scalar
  540.  
  541.        Now for an example of dealing with the items returned from
  542.        a Perl subroutine.
  543.  
  544.        Here is a Perl subroutine, Adder,  which takes 2 integer
  545.        parameters and simply returns their sum.
  546.  
  547.            sub Adder
  548.            {
  549.                my($a, $b) = @_ ;
  550.                $a + $b ;
  551.            }
  552.  
  553.        Since we are now concerned with the return value from
  554.        Adder, the C function required to call it is now a bit
  555.        more complex.
  556.  
  557.            static void
  558.            call_Adder(a, b)
  559.            int a ;
  560.            int b ;
  561.            {
  562.                dSP ;
  563.                int count ;
  564.  
  565.                ENTER ;
  566.                SAVETMPS;
  567.  
  568.                PUSHMARK(sp) ;
  569.                XPUSHs(sv_2mortal(newSViv(a)));
  570.                XPUSHs(sv_2mortal(newSViv(b)));
  571.                PUTBACK ;
  572.  
  573.                count = perl_call_pv("Adder", G_SCALAR);
  574.  
  575.                SPAGAIN ;
  576.  
  577.                if (count != 1)
  578.                    croak("Big trouble\n") ;
  579.  
  580.                printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  581.  
  582.                PUTBACK ;
  583.                FREETMPS ;
  584.                LEAVE ;
  585.            }
  586.  
  587.        Points to note this time are
  588.  
  589.        1.   The only flag specified this time was G_SCALAR. That
  590.             means the @_ array will be created and that the value
  591.             returned by Adder will still exist after the call to
  592.             perl_call_pv.
  593.  
  594.        2.   Because we are interested in what is returned from
  595.             Adder we cannot specify G_DISCARD. This means that we
  596.             will have to tidy up the Perl stack and dispose of
  597.             any temporary values ourselves. This is the purpose
  598.             of
  599.  
  600.                 ENTER ;
  601.                 SAVETMPS ;
  602.  
  603.             at the start of the function, and
  604.  
  605.                 FREETMPS ;
  606.                 LEAVE ;
  607.  
  608.             at the end. The ENTER/SAVETMPS pair creates a
  609.             boundary for any temporaries we create.  This means
  610.             that the temporaries we get rid of will be limited to
  611.             those which were created after these calls.
  612.  
  613.             The FREETMPS/LEAVE pair will get rid of any values
  614.             returned by the Perl subroutine, plus it will also
  615.             dump the mortal SV's we have created.  Having
  616.             ENTER/SAVETMPS at the beginning of the code makes
  617.             sure that no other mortals are destroyed.
  618.  
  619.             Think of these macros as working a bit like using {
  620.             and } in Perl to limit the scope of local variables.
  621.  
  622.             See the section Using Perl to dispose of temporaries
  623.             for details of an alternative to using these macros.
  624.  
  625.        3.   The purpose of the macro SPAGAIN is to refresh the
  626.             local copy of the stack pointer. This is necessary
  627.             because it is possible that the memory allocated to
  628.             the Perl stack has been re-allocated whilst in the
  629.             perl_call_pv call.
  630.  
  631.             If you are making use of the Perl stack pointer in
  632.             your code you must always refresh the your local copy
  633.             using SPAGAIN whenever you make use of the
  634.             perl_call_* functions or any other Perl internal
  635.             function.
  636.  
  637.        4.   Although only a single value was expected to be
  638.             returned from Adder, it is still good practice to
  639.             check the return code from perl_call_pv anyway.
  640.  
  641.             Expecting a single value is not quite the same as
  642.             knowing that there will be one. If someone modified
  643.             Adder to return a list and we didn't check for that
  644.             possibility and take appropriate action the Perl
  645.             stack would end up in an inconsistent state. That is
  646.             something you really don't want to ever happen.
  647.  
  648.        5.   The POPi macro is used here to pop the return value
  649.             from the stack.  In this case we wanted an integer,
  650.             so POPi was used.
  651.  
  652.             Here is the complete list of POP macros available,
  653.             along with the types they return.
  654.  
  655.                 POPs        SV
  656.                 POPp        pointer
  657.                 POPn        double
  658.                 POPi        integer
  659.                 POPl        long
  660.  
  661.        6.   The final PUTBACK is used to leave the Perl stack in
  662.             a consistent state before exiting the function.  This
  663.             is necessary because when we popped the return value
  664.             from the stack with POPi it updated only our local
  665.             copy of the stack pointer.  Remember, PUTBACK sets
  666.             the global stack pointer to be the same as our local
  667.             copy.
  668.  
  669.        Returning a list of values
  670.  
  671.        Now, let's extend the previous example to return both the
  672.        sum of the parameters and the difference.
  673.  
  674.        Here is the Perl subroutine
  675.  
  676.            sub AddSubtract
  677.            {
  678.               my($a, $b) = @_ ;
  679.               ($a+$b, $a-$b) ;
  680.            }
  681.  
  682.        and this is the C function
  683.  
  684.            static void
  685.            call_AddSubtract(a, b)
  686.            int a ;
  687.            int b ;
  688.            {
  689.                dSP ;
  690.                int count ;
  691.  
  692.                ENTER ;
  693.                SAVETMPS;
  694.  
  695.                PUSHMARK(sp) ;
  696.                XPUSHs(sv_2mortal(newSViv(a)));
  697.                XPUSHs(sv_2mortal(newSViv(b)));
  698.                PUTBACK ;
  699.  
  700.                count = perl_call_pv("AddSubtract", G_ARRAY);
  701.  
  702.                SPAGAIN ;
  703.  
  704.                if (count != 2)
  705.                    croak("Big trouble\n") ;
  706.  
  707.                printf ("%d - %d = %d\n", a, b, POPi) ;
  708.                printf ("%d + %d = %d\n", a, b, POPi) ;
  709.  
  710.                PUTBACK ;
  711.                FREETMPS ;
  712.                LEAVE ;
  713.            }
  714.  
  715.        If call_AddSubtract is called like this
  716.  
  717.            call_AddSubtract(7, 4) ;
  718.  
  719.        then here is the output
  720.  
  721.            7 - 4 = 3
  722.            7 + 4 = 11
  723.  
  724.        Notes
  725.  
  726.        1.   We wanted array context, so G_ARRAY was used.
  727.  
  728.        2.   Not surprisingly POPi is used twice this time because
  729.             we were retrieving 2 values from the stack. The
  730.             important thing to note is that when using the POP*
  731.             macros they come off the stack in reverse order.
  732.  
  733.        Returning a list in a scalar context
  734.  
  735.        Say the Perl subroutine in the previous section was called
  736.        in a scalar context, like this
  737.  
  738.            static void
  739.            call_AddSubScalar(a, b)
  740.            int a ;
  741.            int b ;
  742.            {
  743.                dSP ;
  744.                int count ;
  745.                int i ;
  746.  
  747.                ENTER ;
  748.                SAVETMPS;
  749.                PUSHMARK(sp) ;
  750.                XPUSHs(sv_2mortal(newSViv(a)));
  751.                XPUSHs(sv_2mortal(newSViv(b)));
  752.                PUTBACK ;
  753.  
  754.                count = perl_call_pv("AddSubtract", G_SCALAR);
  755.  
  756.                SPAGAIN ;
  757.  
  758.                printf ("Items Returned = %d\n", count) ;
  759.  
  760.                for (i = 1 ; i <= count ; ++i)
  761.                    printf ("Value %d = %d\n", i, POPi) ;
  762.  
  763.                PUTBACK ;
  764.                FREETMPS ;
  765.                LEAVE ;
  766.            }
  767.  
  768.        The other modification made is that call_AddSubScalar will
  769.        print the number of items returned from the Perl
  770.        subroutine and their value (for simplicity it assumes that
  771.        they are integer).  So if call_AddSubScalar is called
  772.  
  773.            call_AddSubScalar(7, 4) ;
  774.  
  775.        then the output will be
  776.  
  777.            Items Returned = 1
  778.            Value 1 = 3
  779.  
  780.        In this case the main point to note is that only the last
  781.        item in the list returned from the subroutine, Adder
  782.        actually made it back to call_AddSubScalar.
  783.  
  784.        Returning Data from Perl via the parameter list
  785.  
  786.        It is also possible to return values directly via the
  787.        parameter list - whether it is actually desirable to do it
  788.        is another matter entirely.
  789.  
  790.        The Perl subroutine, Inc, below takes 2 parameters and
  791.        increments each directly.
  792.  
  793.            sub Inc
  794.            {
  795.                ++ $_[0] ;
  796.                ++ $_[1] ;
  797.            }
  798.  
  799.        and here is a C function to call it.
  800.  
  801.            static void
  802.            call_Inc(a, b)
  803.            int a ;
  804.            int b ;
  805.            {
  806.                dSP ;
  807.                int count ;
  808.                SV * sva ;
  809.                SV * svb ;
  810.  
  811.                ENTER ;
  812.                SAVETMPS;
  813.  
  814.                sva = sv_2mortal(newSViv(a)) ;
  815.                svb = sv_2mortal(newSViv(b)) ;
  816.  
  817.                PUSHMARK(sp) ;
  818.                XPUSHs(sva);
  819.                XPUSHs(svb);
  820.                PUTBACK ;
  821.  
  822.                count = perl_call_pv("Inc", G_DISCARD);
  823.  
  824.                if (count != 0)
  825.                    croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
  826.                           count) ;
  827.  
  828.                printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  829.                printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  830.  
  831.                FREETMPS ;
  832.                LEAVE ;
  833.            }
  834.  
  835.        To be able to access the two parameters that were pushed
  836.        onto the stack after they return from perl_call_pv it is
  837.        necessary to make a note of their addresses - thus the two
  838.        variables sva and svb.
  839.  
  840.        The reason this is necessary is that the area of the Perl
  841.        stack which held them will very likely have been
  842.        overwritten by something else by the time control returns
  843.        from perl_call_pv.
  844.  
  845.        Using G_EVAL
  846.  
  847.        Now an example using G_EVAL. Below is a Perl subroutine
  848.        which computes the difference of its 2 parameters. If this
  849.        would result in a negative result, the subroutine calls
  850.        die.
  851.  
  852.            sub Subtract
  853.            {
  854.                my ($a, $b) = @_ ;
  855.                die "death can be fatal\n" if $a < $b ;
  856.  
  857.                $a - $b ;
  858.            }
  859.  
  860.        and some C to call it
  861.  
  862.            static void
  863.            call_Subtract(a, b)
  864.            int a ;
  865.            int b ;
  866.            {
  867.                dSP ;
  868.                int count ;
  869.  
  870.                ENTER ;
  871.                SAVETMPS;
  872.  
  873.                PUSHMARK(sp) ;
  874.                XPUSHs(sv_2mortal(newSViv(a)));
  875.                XPUSHs(sv_2mortal(newSViv(b)));
  876.                PUTBACK ;
  877.  
  878.                count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  879.  
  880.                SPAGAIN ;
  881.  
  882.                /* Check the eval first */
  883.                if (SvTRUE(GvSV(errgv)))
  884.                {
  885.                    printf ("Uh oh - %s\n", SvPV(GvSV(errgv), na)) ;
  886.                    POPs ;
  887.                }
  888.                else
  889.                {
  890.                    if (count != 1)
  891.                       croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
  892.                                count) ;
  893.  
  894.                    printf ("%d - %d = %d\n", a, b, POPi) ;
  895.                }
  896.  
  897.                PUTBACK ;
  898.                FREETMPS ;
  899.                LEAVE ;
  900.            }
  901.  
  902.        If call_Subtract is called thus
  903.  
  904.            call_Subtract(4, 5)
  905.  
  906.        the following will be printed
  907.  
  908.            Uh oh - death can be fatal
  909.        Notes
  910.  
  911.        1.   We want to be able to catch the die so we have used
  912.             the G_EVAL flag.  Not specifying this flag would mean
  913.             that the program would terminate immediately at the
  914.             die statement in the subroutine Subtract.
  915.  
  916.        2.   The code
  917.  
  918.                 if (SvTRUE(GvSV(errgv)))
  919.                 {
  920.                     printf ("Uh oh - %s\n", SvPV(GvSV(errgv), na)) ;
  921.                     POPs ;
  922.                 }
  923.  
  924.             is the direct equivalent of this bit of Perl
  925.  
  926.                 print "Uh oh - $@\n" if $@ ;
  927.  
  928.             errgv is a perl global of type GV * that points to
  929.             the symbol table entry containing the error.
  930.             GvSV(errgv) therefore refers to the C equivalent of
  931.             $@.
  932.  
  933.        3.   Note that the stack is popped using POPs in the block
  934.             where SvTRUE(GvSV(errgv)) is true.  This is necessary
  935.             because whenever a perl_call_* function invoked with
  936.             G_EVAL|G_SCALAR returns an error, the top of the
  937.             stack holds the value undef. Since we want the
  938.             program to continue after detecting this error, it is
  939.             essential that the stack is tidied up by removing the
  940.             undef.
  941.  
  942.        Using G_KEEPERR
  943.  
  944.        Consider this rather facetious example, where we have used
  945.        an XS version of the call_Subtract example above inside a
  946.        destructor:
  947.  
  948.            package Foo;
  949.            sub new { bless {}, $_[0] }
  950.            sub Subtract {
  951.                my($a,$b) = @_;
  952.                die "death can be fatal" if $a < $b ;
  953.                $a - $b;
  954.            }
  955.            sub DESTROY { call_Subtract(5, 4); }
  956.            sub foo { die "foo dies"; }
  957.  
  958.            package main;
  959.            eval { Foo->new->foo };
  960.            print "Saw: $@" if $@;             # should be, but isn't
  961.  
  962.        This example will fail to recognize that an error occurred
  963.        inside the eval {}.  Here's why: the call_Subtract code
  964.        got executed while perl was cleaning up temporaries when
  965.        exiting the eval block, and since call_Subtract is
  966.        implemented with perl_call_pv using the G_EVAL flag, it
  967.        promptly reset $@.  This results in the failure of the
  968.        outermost test for $@, and thereby the failure of the
  969.        error trap.
  970.  
  971.        Appending the G_KEEPERR flag, so that the perl_call_pv
  972.        call in call_Subtract reads:
  973.  
  974.                count = perl_call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
  975.  
  976.        will preserve the error and restore reliable error
  977.        handling.
  978.  
  979.        Using perl_call_sv
  980.  
  981.        In all the previous examples I have 'hard-wired' the name
  982.        of the Perl subroutine to be called from C.  Most of the
  983.        time though, it is more convenient to be able to specify
  984.        the name of the Perl subroutine from within the Perl
  985.        script.
  986.  
  987.        Consider the Perl code below
  988.  
  989.            sub fred
  990.            {
  991.                print "Hello there\n" ;
  992.            }
  993.  
  994.            CallSubPV("fred") ;
  995.  
  996.        Here is a snippet of XSUB which defines CallSubPV.
  997.  
  998.            void
  999.            CallSubPV(name)
  1000.                char *  name
  1001.                CODE:
  1002.                PUSHMARK(sp) ;
  1003.                perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  1004.  
  1005.        That is fine as far as it goes. The thing is, the Perl
  1006.        subroutine can be specified only as a string.  For Perl 4
  1007.        this was adequate, but Perl 5 allows references to
  1008.        subroutines and anonymous subroutines.  This is where
  1009.        perl_call_sv is useful.
  1010.  
  1011.        The code below for CallSubSV is identical to CallSubPV
  1012.        except that the name parameter is now defined as an SV*
  1013.        and we use perl_call_sv instead of perl_call_pv.
  1014.  
  1015.            void
  1016.            CallSubSV(name)
  1017.                SV *    name
  1018.                CODE:
  1019.                PUSHMARK(sp) ;
  1020.                perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  1021.  
  1022.        Since we are using an SV to call fred the following can
  1023.        all be used
  1024.  
  1025.            CallSubSV("fred") ;
  1026.            CallSubSV(\&fred) ;
  1027.            $ref = \&fred ;
  1028.            CallSubSV($ref) ;
  1029.            CallSubSV( sub { print "Hello there\n" } ) ;
  1030.  
  1031.        As you can see, perl_call_sv gives you much greater
  1032.        flexibility in how you can specify the Perl subroutine.
  1033.  
  1034.        You should note that if it is necessary to store the SV
  1035.        (name in the example above) which corresponds to the Perl
  1036.        subroutine so that it can be used later in the program, it
  1037.        not enough to just store a copy of the pointer to the SV.
  1038.        Say the code above had been like this
  1039.  
  1040.            static SV * rememberSub ;
  1041.  
  1042.            void
  1043.            SaveSub1(name)
  1044.                SV *    name
  1045.                CODE:
  1046.                rememberSub = name ;
  1047.  
  1048.            void
  1049.            CallSavedSub1()
  1050.                CODE:
  1051.                PUSHMARK(sp) ;
  1052.                perl_call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
  1053.  
  1054.        The reason this is wrong is that by the time you come to
  1055.        use the pointer rememberSub in CallSavedSub1, it may or
  1056.        may not still refer to the Perl subroutine that was
  1057.        recorded in SaveSub1.  This is particularly true for these
  1058.        cases
  1059.  
  1060.            SaveSub1(\&fred) ;
  1061.            CallSavedSub1() ;
  1062.  
  1063.            SaveSub1( sub { print "Hello there\n" } ) ;
  1064.            CallSavedSub1() ;
  1065.  
  1066.        By the time each of the SaveSub1 statements above have
  1067.        been executed, the SV*'s which corresponded to the
  1068.        parameters will no longer exist.  Expect an error message
  1069.        from Perl of the form
  1070.  
  1071.            Can't use an undefined value as a subroutine reference at ...
  1072.  
  1073.        for each of the CallSavedSub1 lines.
  1074.  
  1075.        Similarly, with this code
  1076.  
  1077.            $ref = \&fred ;
  1078.            SaveSub1($ref) ;
  1079.            $ref = 47 ;
  1080.            CallSavedSub1() ;
  1081.  
  1082.        you can expect one of these messages (which you actually
  1083.        get is dependant on the version of Perl you are using)
  1084.  
  1085.            Not a CODE reference at ...
  1086.            Undefined subroutine &main::47 called ...
  1087.  
  1088.        The variable $ref may have referred to the subroutine fred
  1089.        whenever the call to SaveSub1 was made but by the time
  1090.        CallSavedSub1 gets called it now holds the number 47.
  1091.        Since we saved only a pointer to the original SV in
  1092.        SaveSub1, any changes to $ref will be tracked by the
  1093.        pointer rememberSub. This means that whenever
  1094.        CallSavedSub1 gets called, it will attempt to execute the
  1095.        code which is referenced by the SV* rememberSub.  In this
  1096.        case though, it now refers to the integer 47, so expect
  1097.        Perl to complain loudly.
  1098.  
  1099.        A similar but more subtle problem is illustrated with this
  1100.        code
  1101.  
  1102.            $ref = \&fred ;
  1103.            SaveSub1($ref) ;
  1104.            $ref = \&joe ;
  1105.            CallSavedSub1() ;
  1106.  
  1107.        This time whenever CallSavedSub1 get called it will
  1108.        execute the Perl subroutine joe (assuming it exists)
  1109.        rather than fred as was originally requested in the call
  1110.        to SaveSub1.
  1111.  
  1112.        To get around these problems it is necessary to take a
  1113.        full copy of the SV.  The code below shows SaveSub2
  1114.        modified to do that
  1115.  
  1116.            static SV * keepSub = (SV*)NULL ;
  1117.  
  1118.            void
  1119.            SaveSub2(name)
  1120.                SV *    name
  1121.                CODE:
  1122.                /* Take a copy of the callback */
  1123.                if (keepSub == (SV*)NULL)
  1124.                    /* First time, so create a new SV */
  1125.                    keepSub = newSVsv(name) ;
  1126.                else
  1127.                    /* Been here before, so overwrite */
  1128.                    SvSetSV(keepSub, name) ;
  1129.  
  1130.            void
  1131.            CallSavedSub2()
  1132.                CODE:
  1133.                PUSHMARK(sp) ;
  1134.                perl_call_sv(keepSub, G_DISCARD|G_NOARGS) ;
  1135.  
  1136.        In order to avoid creating a new SV every time SaveSub2 is
  1137.        called, the function first checks to see if it has been
  1138.        called before.  If not, then space for a new SV is
  1139.        allocated and the reference to the Perl subroutine, name
  1140.        is copied to the variable keepSub in one operation using
  1141.        newSVsv.  Thereafter, whenever SaveSub2 is called the
  1142.        existing SV, keepSub, is overwritten with the new value
  1143.        using SvSetSV.
  1144.  
  1145.        Using perl_call_argv
  1146.  
  1147.        Here is a Perl subroutine which prints whatever parameters
  1148.        are passed to it.
  1149.  
  1150.            sub PrintList
  1151.            {
  1152.                my(@list) = @_ ;
  1153.  
  1154.                foreach (@list) { print "$_\n" }
  1155.            }
  1156.  
  1157.        and here is an example of perl_call_argv which will call
  1158.        PrintList.
  1159.  
  1160.            static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
  1161.  
  1162.            static void
  1163.            call_PrintList()
  1164.            {
  1165.                dSP ;
  1166.  
  1167.                perl_call_argv("PrintList", G_DISCARD, words) ;
  1168.            }
  1169.  
  1170.        Note that it is not necessary to call PUSHMARK in this
  1171.        instance.  This is because perl_call_argv will do it for
  1172.        you.
  1173.  
  1174.        Using perl_call_method
  1175.  
  1176.        Consider the following Perl code
  1177.  
  1178.            {
  1179.                package Mine ;
  1180.  
  1181.                sub new
  1182.                {
  1183.                    my($type) = shift ;
  1184.                    bless [@_]
  1185.                }
  1186.  
  1187.                sub Display
  1188.                {
  1189.                    my ($self, $index) = @_ ;
  1190.                    print "$index: $$self[$index]\n" ;
  1191.                }
  1192.  
  1193.                sub PrintID
  1194.                {
  1195.                    my($class) = @_ ;
  1196.                    print "This is Class $class version 1.0\n" ;
  1197.                }
  1198.            }
  1199.  
  1200.        It just implements a very simple class to manage an array.
  1201.        Apart from the constructor, new, it declares methods, one
  1202.        static and one virtual. The static method, PrintID, simply
  1203.        prints out the class name and a version number. The
  1204.        virtual method, Display, prints out a single element of
  1205.        the array.  Here is an all Perl example of using it.
  1206.  
  1207.            $a = new Mine ('red', 'green', 'blue') ;
  1208.            $a->Display(1) ;
  1209.            PrintID Mine;
  1210.  
  1211.        will print
  1212.  
  1213.            1: green
  1214.            This is Class Mine version 1.0
  1215.  
  1216.        Calling a Perl method from C is fairly straightforward.
  1217.        The following things are required
  1218.  
  1219.        o    a reference to the object for a virtual method or the
  1220.             name of the class for a static method.
  1221.  
  1222.        o    the name of the method.
  1223.  
  1224.        o    any other parameters specific to the method.
  1225.  
  1226.        Here is a simple XSUB which illustrates the mechanics of
  1227.        calling both the PrintID and Display methods from C.
  1228.  
  1229.            void
  1230.            call_Method(ref, method, index)
  1231.                SV *    ref
  1232.                char *  method
  1233.                int             index
  1234.                CODE:
  1235.                PUSHMARK(sp);
  1236.                XPUSHs(ref);
  1237.                XPUSHs(sv_2mortal(newSViv(index))) ;
  1238.                PUTBACK;
  1239.  
  1240.                perl_call_method(method, G_DISCARD) ;
  1241.  
  1242.            void
  1243.            call_PrintID(class, method)
  1244.                char *  class
  1245.                char *  method
  1246.                CODE:
  1247.                PUSHMARK(sp);
  1248.                XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
  1249.                PUTBACK;
  1250.  
  1251.                perl_call_method(method, G_DISCARD) ;
  1252.  
  1253.        So the methods PrintID and Display can be invoked like
  1254.        this
  1255.  
  1256.            $a = new Mine ('red', 'green', 'blue') ;
  1257.            call_Method($a, 'Display', 1) ;
  1258.            call_PrintID('Mine', 'PrintID') ;
  1259.  
  1260.        The only thing to note is that in both the static and
  1261.        virtual methods, the method name is not passed via the
  1262.        stack - it is used as the first parameter to
  1263.        perl_call_method.
  1264.  
  1265.        Using GIMME
  1266.  
  1267.        Here is a trivial XSUB which prints the context in which
  1268.        it is currently executing.
  1269.  
  1270.            void
  1271.            PrintContext()
  1272.                CODE:
  1273.                if (GIMME == G_SCALAR)
  1274.                    printf ("Context is Scalar\n") ;
  1275.                else
  1276.                    printf ("Context is Array\n") ;
  1277.  
  1278.        and here is some Perl to test it
  1279.  
  1280.            $a = PrintContext ;
  1281.            @a = PrintContext ;
  1282.  
  1283.        The output from that will be
  1284.  
  1285.            Context is Scalar
  1286.            Context is Array
  1287.  
  1288.        Using Perl to dispose of temporaries
  1289.  
  1290.        In the examples given to date, any temporaries created in
  1291.        the callback (i.e. parameters passed on the stack to the
  1292.        perl_call_* function or values returned via the stack)
  1293.        have been freed by one of these methods
  1294.  
  1295.        o    specifying the G_DISCARD flag with perl_call_*.
  1296.  
  1297.        o    explicitly disposed of using the ENTER/SAVETMPS -
  1298.             FREETMPS/LEAVE pairing.
  1299.  
  1300.        There is another method which can be used, namely letting
  1301.        Perl do it for you automatically whenever it regains
  1302.        control after the callback has terminated.  This is done
  1303.        by simply not using the
  1304.  
  1305.            ENTER ;
  1306.            SAVETMPS ;
  1307.            ...
  1308.            FREETMPS ;
  1309.            LEAVE ;
  1310.  
  1311.        sequence in the callback (and not, of course, specifying
  1312.        the G_DISCARD flag).
  1313.  
  1314.        If you are going to use this method you have to be aware
  1315.        of a possible memory leak which can arise under very
  1316.        specific circumstances.  To explain these circumstances
  1317.        you need to know a bit about the flow of control between
  1318.        Perl and the callback routine.
  1319.  
  1320.        The examples given at the start of the document (an error
  1321.        handler and an event driven program) are typical of the
  1322.        two main sorts of flow control that you are likely to
  1323.        encounter with callbacks.  There is a very important
  1324.        distinction between them, so pay attention.
  1325.  
  1326.        In the first example, an error handler, the flow of
  1327.        control could be as follows.  You have created an
  1328.        interface to an external library.  Control can reach the
  1329.        external library like this
  1330.  
  1331.            perl --> XSUB --> external library
  1332.  
  1333.        Whilst control is in the library, an error condition
  1334.        occurs. You have previously set up a Perl callback to
  1335.        handle this situation, so it will get executed. Once the
  1336.        callback has finished, control will drop back to Perl
  1337.        again.  Here is what the flow of control will be like in
  1338.        that situation
  1339.  
  1340.            perl --> XSUB --> external library
  1341.                              ...
  1342.                              error occurs
  1343.                              ...
  1344.                              external library --> perl_call --> perl
  1345.                                                                  |
  1346.            perl <-- XSUB <-- external library <-- perl_call <----+
  1347.  
  1348.        After processing of the error using perl_call_* is
  1349.        completed, control reverts back to Perl more or less
  1350.        immediately.
  1351.  
  1352.        In the diagram, the further right you go the more deeply
  1353.        nested the scope is.  It is only when control is back with
  1354.        perl on the extreme left of the diagram that you will have
  1355.        dropped back to the enclosing scope and any temporaries
  1356.        you have left hanging around will be freed.
  1357.  
  1358.        In the second example, an event driven program, the flow
  1359.        of control will be more like this
  1360.  
  1361.            perl --> XSUB --> event handler
  1362.                              ...
  1363.                              event handler --> perl_call --> perl
  1364.                                                               |
  1365.                              event handler <-- perl_call --<--+
  1366.                              ...
  1367.                              event handler --> perl_call --> perl
  1368.                                                               |
  1369.                              event handler <-- perl_call --<--+
  1370.                              ...
  1371.                              event handler --> perl_call --> perl
  1372.                                                               |
  1373.                              event handler <-- perl_call --<--+
  1374.  
  1375.        In this case the flow of control can consist of only the
  1376.        repeated sequence
  1377.  
  1378.            event handler --> perl_call --> perl
  1379.  
  1380.        for the practically the complete duration of the program.
  1381.        This means that control may never drop back to the
  1382.        surrounding scope in Perl at the extreme left.
  1383.  
  1384.        So what is the big problem? Well, if you are expecting
  1385.        Perl to tidy up those temporaries for you, you might be in
  1386.        for a long wait.  For Perl to actually dispose of your
  1387.        temporaries, control must drop back to the enclosing scope
  1388.        at some stage.  In the event driven scenario that may
  1389.        never happen.  This means that as time goes on, your
  1390.        program will create more and more temporaries, none of
  1391.        which will ever be freed. As each of these temporaries
  1392.        consumes some memory your program will eventually consume
  1393.        all the available memory in your system - kapow!
  1394.  
  1395.        So here is the bottom line - if you are sure that control
  1396.        will revert back to the enclosing Perl scope fairly
  1397.        quickly after the end of your callback, then it isn't
  1398.        absolutely necessary to explicitly dispose of any
  1399.        temporaries you may have created. Mind you, if you are at
  1400.        all uncertain about what to do, it doesn't do any harm to
  1401.        tidy up anyway.
  1402.  
  1403.        Strategies for storing Callback Context Information
  1404.  
  1405.        Potentially one of the trickiest problems to overcome when
  1406.        designing a callback interface can be figuring out how to
  1407.        store the mapping between the C callback function and the
  1408.        Perl equivalent.
  1409.  
  1410.        To help understand why this can be a real problem first
  1411.        consider how a callback is set up in an all C environment.
  1412.        Typically a C API will provide a function to register a
  1413.        callback.  This will expect a pointer to a function as one
  1414.        of its parameters.  Below is a call to a hypothetical
  1415.        function register_fatal which registers the C function to
  1416.        get called when a fatal error occurs.
  1417.  
  1418.            register_fatal(cb1) ;
  1419.  
  1420.        The single parameter cb1 is a pointer to a function, so
  1421.        you must have defined cb1 in your code, say something like
  1422.        this
  1423.  
  1424.            static void
  1425.            cb1()
  1426.            {
  1427.                printf ("Fatal Error\n") ;
  1428.                exit(1) ;
  1429.            }
  1430.  
  1431.        Now change that to call a Perl subroutine instead
  1432.  
  1433.            static SV * callback = (SV*)NULL;
  1434.  
  1435.            static void
  1436.            cb1()
  1437.            {
  1438.                dSP ;
  1439.  
  1440.                PUSHMARK(sp) ;
  1441.                /* Call the Perl sub to process the callback */
  1442.                perl_call_sv(callback, G_DISCARD) ;
  1443.            }
  1444.  
  1445.            void
  1446.            register_fatal(fn)
  1447.                SV *    fn
  1448.                CODE:
  1449.                /* Remember the Perl sub */
  1450.                if (callback == (SV*)NULL)
  1451.                    callback = newSVsv(fn) ;
  1452.                else
  1453.                    SvSetSV(callback, fn) ;
  1454.  
  1455.                /* register the callback with the external library */
  1456.                register_fatal(cb1) ;
  1457.  
  1458.        where the Perl equivalent of register_fatal and the
  1459.        callback it registers, pcb1, might look like this
  1460.  
  1461.            # Register the sub pcb1
  1462.            register_fatal(\&pcb1) ;
  1463.  
  1464.            sub pcb1
  1465.            {
  1466.                die "I'm dying...\n" ;
  1467.            }
  1468.  
  1469.        The mapping between the C callback and the Perl equivalent
  1470.        is stored in the global variable callback.
  1471.  
  1472.        This will be adequate if you ever need to have only 1
  1473.        callback registered at any time. An example could be an
  1474.        error handler like the code sketched out above. Remember
  1475.        though, repeated calls to register_fatal will replace the
  1476.        previously registered callback function with the new one.
  1477.  
  1478.        Say for example you want to interface to a library which
  1479.        allows asynchronous file i/o.  In this case you may be
  1480.        able to register a callback whenever a read operation has
  1481.        completed. To be of any use we want to be able to call
  1482.        separate Perl subroutines for each file that is opened.
  1483.        As it stands, the error handler example above would not be
  1484.        adequate as it allows only a single callback to be defined
  1485.        at any time. What we require is a means of storing the
  1486.        mapping between the opened file and the Perl subroutine we
  1487.        want to be called for that file.
  1488.  
  1489.        Say the i/o library has a function asynch_read which
  1490.        associates a C function ProcessRead with a file handle fh
  1491.        - this assumes that it has also provided some routine to
  1492.        open the file and so obtain the file handle.
  1493.  
  1494.            asynch_read(fh, ProcessRead)
  1495.        This may expect the C ProcessRead function of this form
  1496.  
  1497.            void
  1498.            ProcessRead(fh, buffer)
  1499.            int fh ;
  1500.            char *      buffer ;
  1501.            {
  1502.                 ...
  1503.            }
  1504.  
  1505.        To provide a Perl interface to this library we need to be
  1506.        able to map between the fh parameter and the Perl
  1507.        subroutine we want called.  A hash is a convenient
  1508.        mechanism for storing this mapping.  The code below shows
  1509.        a possible implementation
  1510.  
  1511.            static HV * Mapping = (HV*)NULL ;
  1512.  
  1513.            void
  1514.            asynch_read(fh, callback)
  1515.                int     fh
  1516.                SV *    callback
  1517.                CODE:
  1518.                /* If the hash doesn't already exist, create it */
  1519.                if (Mapping == (HV*)NULL)
  1520.                    Mapping = newHV() ;
  1521.  
  1522.                /* Save the fh -> callback mapping */
  1523.                hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
  1524.  
  1525.                /* Register with the C Library */
  1526.                asynch_read(fh, asynch_read_if) ;
  1527.  
  1528.        and asynch_read_if could look like this
  1529.  
  1530.            static void
  1531.            asynch_read_if(fh, buffer)
  1532.            int fh ;
  1533.            char *      buffer ;
  1534.            {
  1535.                dSP ;
  1536.                SV ** sv ;
  1537.  
  1538.                /* Get the callback associated with fh */
  1539.                sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
  1540.                if (sv == (SV**)NULL)
  1541.                    croak("Internal error...\n") ;
  1542.  
  1543.                PUSHMARK(sp) ;
  1544.                XPUSHs(sv_2mortal(newSViv(fh))) ;
  1545.                XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1546.                PUTBACK ;
  1547.  
  1548.                /* Call the Perl sub */
  1549.                perl_call_sv(*sv, G_DISCARD) ;
  1550.            }
  1551.  
  1552.        For completeness, here is asynch_close.  This shows how to
  1553.        remove the entry from the hash Mapping.
  1554.  
  1555.            void
  1556.            asynch_close(fh)
  1557.                int     fh
  1558.                CODE:
  1559.                /* Remove the entry from the hash */
  1560.                (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
  1561.  
  1562.                /* Now call the real asynch_close */
  1563.                asynch_close(fh) ;
  1564.  
  1565.        So the Perl interface would look like this
  1566.  
  1567.            sub callback1
  1568.            {
  1569.                my($handle, $buffer) = @_ ;
  1570.            }
  1571.  
  1572.            # Register the Perl callback
  1573.            asynch_read($fh, \&callback1) ;
  1574.  
  1575.            asynch_close($fh) ;
  1576.  
  1577.        The mapping between the C callback and Perl is stored in
  1578.        the global hash Mapping this time. Using a hash has the
  1579.        distinct advantage that it allows an unlimited number of
  1580.        callbacks to be registered.
  1581.  
  1582.        What if the interface provided by the C callback doesn't
  1583.        contain a parameter which allows the file handle to Perl
  1584.        subroutine mapping?  Say in the asynchronous i/o package,
  1585.        the callback function gets passed only the buffer
  1586.        parameter like this
  1587.  
  1588.            void
  1589.            ProcessRead(buffer)
  1590.            char *      buffer ;
  1591.            {
  1592.                ...
  1593.            }
  1594.  
  1595.        Without the file handle there is no straightforward way to
  1596.        map from the C callback to the Perl subroutine.
  1597.  
  1598.        In this case a possible way around this problem is to pre-
  1599.        define a series of C functions to act as the interface to
  1600.        Perl, thus
  1601.  
  1602.            #define MAX_CB              3
  1603.            #define NULL_HANDLE -1
  1604.            typedef void (*FnMap)() ;
  1605.  
  1606.            struct MapStruct {
  1607.                FnMap    Function ;
  1608.                SV *     PerlSub ;
  1609.                int      Handle ;
  1610.              } ;
  1611.  
  1612.            static void  fn1() ;
  1613.            static void  fn2() ;
  1614.            static void  fn3() ;
  1615.  
  1616.            static struct MapStruct Map [MAX_CB] =
  1617.                {
  1618.                    { fn1, NULL, NULL_HANDLE },
  1619.                    { fn2, NULL, NULL_HANDLE },
  1620.                    { fn3, NULL, NULL_HANDLE }
  1621.                } ;
  1622.  
  1623.            static void
  1624.            Pcb(index, buffer)
  1625.            int index ;
  1626.            char * buffer ;
  1627.            {
  1628.                dSP ;
  1629.  
  1630.                PUSHMARK(sp) ;
  1631.                XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1632.                PUTBACK ;
  1633.  
  1634.                /* Call the Perl sub */
  1635.                perl_call_sv(Map[index].PerlSub, G_DISCARD) ;
  1636.            }
  1637.  
  1638.            static void
  1639.            fn1(buffer)
  1640.            char * buffer ;
  1641.            {
  1642.                Pcb(0, buffer) ;
  1643.            }
  1644.  
  1645.            static void
  1646.            fn2(buffer)
  1647.            char * buffer ;
  1648.            {
  1649.                Pcb(1, buffer) ;
  1650.            }
  1651.  
  1652.            static void
  1653.            fn3(buffer)
  1654.            char * buffer ;
  1655.            {
  1656.                Pcb(2, buffer) ;
  1657.            }
  1658.  
  1659.            void
  1660.            array_asynch_read(fh, callback)
  1661.                int             fh
  1662.                SV *    callback
  1663.                CODE:
  1664.                int index ;
  1665.                int null_index = MAX_CB ;
  1666.  
  1667.                /* Find the same handle or an empty entry */
  1668.                for (index = 0 ; index < MAX_CB ; ++index)
  1669.                {
  1670.                    if (Map[index].Handle == fh)
  1671.                        break ;
  1672.  
  1673.                    if (Map[index].Handle == NULL_HANDLE)
  1674.                        null_index = index ;
  1675.                }
  1676.  
  1677.                if (index == MAX_CB && null_index == MAX_CB)
  1678.                    croak ("Too many callback functions registered\n") ;
  1679.  
  1680.                if (index == MAX_CB)
  1681.                    index = null_index ;
  1682.  
  1683.                /* Save the file handle */
  1684.                Map[index].Handle = fh ;
  1685.  
  1686.                /* Remember the Perl sub */
  1687.                if (Map[index].PerlSub == (SV*)NULL)
  1688.                    Map[index].PerlSub = newSVsv(callback) ;
  1689.                else
  1690.                    SvSetSV(Map[index].PerlSub, callback) ;
  1691.  
  1692.                asynch_read(fh, Map[index].Function) ;
  1693.  
  1694.            void
  1695.            array_asynch_close(fh)
  1696.                int     fh
  1697.                CODE:
  1698.                int index ;
  1699.  
  1700.                /* Find the file handle */
  1701.                for (index = 0; index < MAX_CB ; ++ index)
  1702.                    if (Map[index].Handle == fh)
  1703.                        break ;
  1704.  
  1705.                if (index == MAX_CB)
  1706.                    croak ("could not close fh %d\n", fh) ;
  1707.  
  1708.                Map[index].Handle = NULL_HANDLE ;
  1709.                SvREFCNT_dec(Map[index].PerlSub) ;
  1710.                Map[index].PerlSub = (SV*)NULL ;
  1711.  
  1712.                asynch_close(fh) ;
  1713.  
  1714.        In this case the functions fn1, fn2 and fn3 are used to
  1715.        remember the Perl subroutine to be called. Each of the
  1716.        functions holds a separate hard-wired index which is used
  1717.        in the function Pcb to access the Map array and actually
  1718.        call the Perl subroutine.
  1719.  
  1720.        There are some obvious disadvantages with this technique.
  1721.  
  1722.        Firstly, the code is considerably more complex than with
  1723.        the previous example.
  1724.  
  1725.        Secondly, there is a hard-wired limit (in this case 3) to
  1726.        the number of callbacks that can exist simultaneously. The
  1727.        only way to increase the limit is by modifying the code to
  1728.        add more functions and then re-compiling.  None the less,
  1729.        as long as the number of functions is chosen with some
  1730.        care, it is still a workable solution and in some cases is
  1731.        the only one available.
  1732.  
  1733.        To summarize, here are a number of possible methods for
  1734.        you to consider for storing the mapping between C and the
  1735.        Perl callback
  1736.  
  1737.        1. Ignore the problem - Allow only 1 callback
  1738.             For a lot of situations, like interfacing to an error
  1739.             handler, this may be a perfectly adequate solution.
  1740.  
  1741.        2. Create a sequence of callbacks - hard wired limit
  1742.             If it is impossible to tell from the parameters
  1743.             passed back from the C callback what the context is,
  1744.             then you may need to create a sequence of C callback
  1745.             interface functions, and store pointers to each in an
  1746.             array.
  1747.  
  1748.        3. Use a parameter to map to the Perl callback
  1749.             A hash is an ideal mechanism to store the mapping
  1750.             between C and Perl.
  1751.  
  1752.        Alternate Stack Manipulation
  1753.  
  1754.        Although I have made use of only the POP* macros to access
  1755.        values returned from Perl subroutines, it is also possible
  1756.        to bypass these macros and read the stack using the ST
  1757.        macro (See the perlxs manpage for a full description of
  1758.        the ST macro).
  1759.        Most of the time the POP* macros should be adequate, the
  1760.        main problem with them is that they force you to process
  1761.        the returned values in sequence. This may not be the most
  1762.        suitable way to process the values in some cases. What we
  1763.        want is to be able to access the stack in a random order.
  1764.        The ST macro as used when coding an XSUB is ideal for this
  1765.        purpose.
  1766.  
  1767.        The code below is the example given in the section
  1768.        Returning a list of values recoded to use ST instead of
  1769.        POP*.
  1770.  
  1771.            static void
  1772.            call_AddSubtract2(a, b)
  1773.            int a ;
  1774.            int b ;
  1775.            {
  1776.                dSP ;
  1777.                I32 ax ;
  1778.                int count ;
  1779.  
  1780.                ENTER ;
  1781.                SAVETMPS;
  1782.  
  1783.                PUSHMARK(sp) ;
  1784.                XPUSHs(sv_2mortal(newSViv(a)));
  1785.                XPUSHs(sv_2mortal(newSViv(b)));
  1786.                PUTBACK ;
  1787.  
  1788.                count = perl_call_pv("AddSubtract", G_ARRAY);
  1789.  
  1790.                SPAGAIN ;
  1791.                sp -= count ;
  1792.                ax = (sp - stack_base) + 1 ;
  1793.  
  1794.                if (count != 2)
  1795.                    croak("Big trouble\n") ;
  1796.  
  1797.                printf ("%d + %d = %d\n", a, b, SvIV(ST(0))) ;
  1798.                printf ("%d - %d = %d\n", a, b, SvIV(ST(1))) ;
  1799.  
  1800.                PUTBACK ;
  1801.                FREETMPS ;
  1802.                LEAVE ;
  1803.            }
  1804.  
  1805.        Notes
  1806.  
  1807.        1.   Notice that it was necessary to define the variable
  1808.             ax.  This is because the ST macro expects it to
  1809.             exist.  If we were in an XSUB it would not be
  1810.             necessary to define ax as it is already defined for
  1811.             you.
  1812.  
  1813.        2.   The code
  1814.  
  1815.                     SPAGAIN ;
  1816.                     sp -= count ;
  1817.                     ax = (sp - stack_base) + 1 ;
  1818.  
  1819.             sets the stack up so that we can use the ST macro.
  1820.  
  1821.        3.   Unlike the original coding of this example, the
  1822.             returned values are not accessed in reverse order.
  1823.             So ST(0) refers to the first value returned by the
  1824.             Perl subroutine and ST(count-1) refers to the last.
  1825.  
  1826. SEE ALSO
  1827.        the perlxs manpage, the perlguts manpage, the perlembed
  1828.        manpage
  1829.  
  1830. AUTHOR
  1831.        Paul Marquess <pmarquess@bfsec.bt.co.uk>
  1832.  
  1833.        Special thanks to the following people who assisted in the
  1834.        creation of the document.
  1835.  
  1836.        Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem,
  1837.        Gurusamy Sarathy and Larry Wall.
  1838.  
  1839. DATE
  1840.        Version 1.2, 16th Jan 1996
  1841.